package org.itboys.core.service.mysql.web;

import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.store.SundayStoreNumMapper;
import org.itboys.core.entity.mysql.SundayProduct;
import org.itboys.core.entity.mysql.SundaySku;
import org.itboys.core.entity.mysql.SundayStoreNum;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * @Author：贾琦磊
 * @Date：2018/8/24
 * @Description：库存service
 */
@Service
public class SundayStoreNumService extends BaseMySqlService<SundayStoreNum>{
    @Autowired
    private SundayStoreNumMapper storeNumMapper;
    @Autowired
    private SundaySkuService skuService;
    @Autowired
    private SundayProductService productService;

    /**
     *清空库存
     * @param preStoreId
     */
    public void clear(Long preStoreId){

    }

    public PageResult<SundayStoreNum> findByStoreId(HttpServletRequest request){
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "storeId");
        List<SundayStoreNum> data = storeNumMapper.select(param);
        Serializable count = storeNumMapper.count(param);
        Set<Long> skuIds=new HashSet<>();
        for (SundayStoreNum s:data
             ) {
            skuIds.add(s.getSKUId());
        }
        if(skuIds.size()>0){
            param.clear();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("ids",skuIds);
            List<SundaySku> skus = skuService.select(param);
            Set<Long> productIds=new HashSet<>();
            for (SundaySku s:skus
                 ) {
                productIds.add(s.getProductId());
            }
            param.put("ids",productIds);
            List<SundayProduct> products = productService.select(param);
            for (SundayStoreNum num:data
                 ) {
                for (SundaySku sku:skus
                     ) {
                    if(num.getSKUId().equals(sku.getId())){
                        num.setNumber(sku.getNumber());
                        for (SundayProduct p:products
                             ) {
                            if(sku.getProductId().equals(p.getId())){
                                num.setProductName(p.getName());
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        return new PageResult<SundayStoreNum>(data,Long.valueOf(count.toString()));
    }
}
